package com.br.aiops.listeners.ladder;

import com.br.aiops.counter.AlertLogCounter;
import com.br.aiops.events.CountEvent;
import com.br.aiops.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class LadderListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(LadderListener.class);

    @EventListener(condition = "#event.getAlertLogCounter().shouldLadderAlert()")
    public synchronized void handlerEvent(CountEvent event) {
        LOGGER.debug("收到事件: {}", event);
        AlertLogCounter counter = event.getAlertLogCounter();
        AbstractLadderJudge judge = getLadderJudge(counter);
        judge.judgeLadder();
    }

    private AbstractLadderJudge getLadderJudge(AlertLogCounter counter) {
        if (counter.getRule().getLadderType() == Constants.LADDER_TYPE_TIMES) {
            return new AlertCountLadderJudge(counter);
        } else if (counter.getRule().getLadderType() == Constants.LADDER_TYPE_DURATION) {
            return new DurationLadderJudge(counter);
        } else if (counter.getRule().getLadderType() == Constants.LADDER_TYPE_DURATION_AND_TIMES) {
            return new DurationAndAlertCountLadderJudge(counter);
        } else if (counter.getRule().getLadderType() == Constants.LADDER_TYPE_DURATION_OR_TIMES) {
            return new DurationOrAlertCountLadderJudge(counter);
        }
        LOGGER.error("未知阶梯类型：{}", counter.getRule().getLadderType());
        throw new IllegalArgumentException("未知阶梯类型");
    }
}
